package cn.lger.security;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录过滤器
 *
 * @author Pro
 * @date 2017/6/18
 */
@WebFilter(urlPatterns = {"/user/*", "/api/user/*"})
public class ClientFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取session中的用户，如果不存在，说明没有登录
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            //获取用户需要访问的完整url
            String url = request.getRequestURL().toString();
            //将访问的完整地址保存
            request.getSession().setAttribute("url", url);
            //要求用户登录，转到登录页面
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);

        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {
    }

}
